<?php
App::import('Core', 'HttpSocket');
//App::import('component','Qdmail');
class MainController extends AppController {
	var $name = 'Main';
	var $layout = "display";
	var $uses = array('Searchcondition','Users');
	var $helpers = array('Form','Number','Ajax', 'Javascript','Cache');
	var $components = array('Bench','Auth','Apikey','Security');
	
	//Auth認証不要のアクション
	var $auth_allow = array(
		'main',
		'help',
		'help_mainmenu',
		'help_userregist',
		'help_userdel',
		'help_login',
		'help_search',
		'help_fav',
		'help_premium',
		'help_repassword',
		'help_environment',
		'history',
		'contact',
		'riyoukiyaku',
		'userregist',
		'regist',	
		'dspuserregist',
		'closed',
		'premium',
		'paypalcallback',
		'search'
	);
	
	//ビューキャッシュを許可するアクションと秒数
	var $cacheAction = array(
		'help' => 60,
		'help_mainmenu' => 60,
		'help_userregist' => 60,
		'help_userdel' => 60,
		'help_login' => 60,
		'help_search' => 60,
		'help_fav' => 60,
		'help_premium' => 60,
		'help_repassword' => 60,
		'help_environment' => 60,
		'history' => 60,
		'contact' => 60,
		'riyoukiyaku' => 60,
		'userregist' => 60,
		'premium' => 60,
	);
	
	var $controller_title = '';
	
	//==========================================================================
	//コールバック
	//==========================================================================
	function beforeFilter(){	
		
		//AppController::beforeFilter()を処理
		parent::beforeFilter();
		
		
	}
		
	//----------------------------------------------------------------
	//メイン初期アクション
	//----------------------------------------------------------------
	function main(){
		
		//ログイン済みであれば検索条件入力画面へ遷移、無ければメイン画面へ
		
		$shopid = $this->Auth->user('shopid');
		if (empty($shopid)){
			//存在しないので登録画面へ遷移を行う
			$this->_pageTitle(SITE_NAME.' : 登録/ログイン画面', true);
			$this->render('main');
		}
		else{
		    //設定済みなので検索条件入力画面へ遷移
	        //ショップIDを格納
	        $this->set('shopid', $shopid);
	        
		    $this->set('all_count', -1);
		    
		    //画面遷移
			$this->_pageTitle(SITE_NAME.' : 検索画面',true);
			$this->render('searchdsp');
		}
	}
		
	//----------------------------------------------------------------
	//検索処理
	//----------------------------------------------------------------
	function search(){
		$this->_pageTitle(SITE_NAME.' : 検索画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if (empty($shopid)){
			//未ログインのため何もしないで終了
			$this->securityerror();
			return;
		}
		//画面に入力された値を取得
		//$this->Searchcondition->set($this->data);
		if (empty($this->data)){
			$this->securityerror();
			return;
		}
		
		$api_Key = $this->Apikey->getApiKey($shopid);
		
		//現在のページ数をパラメータより取得
		//$page_index = $this->params['pass'][0];
		$page_index = 0;
	
		//入力された検索項目をパラメータに変換
		//ページ位置
		$param = '&page_index='. $page_index;
	
		//検索語
		if (!empty($this->data['Searchcondition']['words'])){
			if(empty($param)){
				$param = '&words='. $this->data['Searchcondition']['words'];
			}
			else{
				$param = $param. '&words='. $this->data['Searchcondition']['words'];
			}
		}
		//カテゴリコード
		if (!empty($this->data['Searchcondition']['article_kocategory_code'])){
			if(empty($param)){
				$param = '&article_category_code='. $this->data['Searchcondition']['article_kocategory_code'];
			}
			else{
				$param = $param. '&article_category_code='. $this->data['Searchcondition']['article_kocategory_code'];
			}
		}
		elseif (!empty($this->data['Searchcondition']['article_category_code'])){
			if(empty($param)){
				$param = '&article_category_code='. sprintf("%02s\n",$this->data['Searchcondition']['article_category_code']);
			}
			else{
				$param = $param. '&article_category_code='. sprintf("%02s\n",$this->data['Searchcondition']['article_category_code']);
			}
		}
		//新着商品
		if ($this->data['Searchcondition']['newly'] == '1'){
			if(empty($param)){
				$param = '&is_newly='. $this->data['Searchcondition']['newly'];
			}
			else{
				$param = $param. '&is_newly='. $this->data['Searchcondition']['newly'];
			}
		}
		//ヒット実績あり
		if ($this->data['Searchcondition']['salable'] == '1' ){
			if(empty($param)){
				$param = '&is_salable='. $this->data['Searchcondition']['salable'];
			}
			else{
				$param = $param. '&is_salable='. $this->data['Searchcondition']['salable'];
			}
		}
		//即日配送
		if ($this->data['Searchcondition']['delivery_sameday'] == '1'){
			if(empty($param)){
				$param = '&is_delivery_sameday='. $this->data['Searchcondition']['delivery_sameday'];
			}
			else{
				$param = $param. '&is_delivery_sameday='. $this->data['Searchcondition']['delivery_sameday'];
			}
		}
		//送料無料
		if ($this->data['Searchcondition']['free_shipping'] == '1'){
			if(empty($param)){
				$param = '&is_free_shipping='. $this->data['Searchcondition']['free_shipping'];
			}
			else{
				$param = $param. '&is_free_shipping='. $this->data['Searchcondition']['free_shipping'];
			}
		}
		//在庫状況コード
		if (!empty($this->data['Searchcondition']['stock_status'])){
			if(empty($param)){
				$param = '&stock_status='. $this->data['Searchcondition']['stock_status'] ;
			}
			else{
				$param = $param. '&stock_status='. $this->data['Searchcondition']['stock_status'] ;
			}
		}
		//在庫の有無
		if (!empty($this->data['Searchcondition']['exists_stock'])){
			if(empty($param)){
				$param = '&exists_stock='. $this->data['Searchcondition']['exists_stock'];
			}
			else{
				$param = $param. '&exists_stock='. $this->data['Searchcondition']['exists_stock'];
			}
		}
		//商品ID
		if (!empty($this->data['Searchcondition']['article_id'])){
			if(empty($param)){
				$param = '&article_id='. $this->data['Searchcondition']['article_id'];
			}
			else{
				$param = $param. '&article_id='. $this->data['Searchcondition']['article_id'];
			}
		}
		//標準利益価格 From
		if (!empty($this->data['Searchcondition']['default_profit_price_from'])){
			if(empty($param)){
				$param = '&default_profit_price_from='. $this->data['Searchcondition']['default_profit_price_from'];
			}
			else{
				$param = $param. '&default_profit_price_from='. $this->data['Searchcondition']['default_profit_price_from'];
			}
		}
		//標準利益価格 To
		if (!empty($this->data['Searchcondition']['default_profit_price_to'])){
			if(empty($param)){
				$param = '&default_profit_price_to='. $this->data['Searchcondition']['default_profit_price_to'];
			}
			else{
				$param = $param. '&default_profit_price_to='. $this->data['Searchcondition']['default_profit_price_to'];
			}
		}
		//販売価格設定状況
		if ($this->data['Searchcondition']['has_shop_price'] == '1' ){
			if(empty($param)){
				$param = '&has_shop_price=registered';
			}
			else{
				$param = $param. '&has_shop_price=registered';
			}
		}
		
		//取得商品数
		$list_per_page = '10';
		if (!empty($this->data['Searchcondition']['list_per_page'])){
			$list_per_page = $this->data['Searchcondition']['list_per_page'];
			if(empty($param)){
				$param = '&list_per_page='. $this->data['Searchcondition']['list_per_page'];
			}
			else{
				$param = $param. '&list_per_page='. $this->data['Searchcondition']['list_per_page'];
			}
		}
		else{
		}
		//並び順
		if (!empty($this->data['Searchcondition']['sort_order'])){
			if(empty($param)){
				$param = '&sort_order='. $this->data['Searchcondition']['sort_order'];
			}
			else{
				$param = $param. '&sort_order='. $this->data['Searchcondition']['sort_order'];
			}
		}
		
		//もしもAPIで検索
		$socket = new HttpSocket();
		if(empty($param)){
			$url = 'http://api.moshimo.com/article/search.xml?authorization_code='. $api_Key;
		}
		else{
			$url = 'http://api.moshimo.com/article/search.xml?authorization_code='. $api_Key. $param;
		}
		
		
		$results = $socket->get($url);
        $getxml = simplexml_load_string($results); 

        $Totalcount=$getxml->Found;
        
	    $i=0;
        if($Totalcount == 0){
		    $this->set('all_count', $Totalcount);
			$this->render('searchdsp');
    		return;
        }
        else{
        	//$TotalPages=ceil($Totalcount/10);
		   foreach($getxml->Articles->Article as $data){

		   	  $item[$i]['article_id']=trim($data->ArticleId);
			  $item[$i]['name']=$data->Name;
			  $item[$i]['descript']=$data->Description;
			  $item[$i]['descript_b']=mb_substr(strip_tags($item[$i]['descript']),0,120,'UTF-8').'...';
			  $item[$i]['special_descript']=$data->SpecialDescription;
			  $item[$i]['catch_copy']=$data->CatchCopy;
			  $item[$i]['spec']=$data->Spec;
			  $item[$i]['image_code']=trim($data->ImageCode);
			  $item[$i]['image_count']=$data->ImageCount;
			  $item[$i]['price']=number_format((int)$data->ShopPrice);
			  $item[$i]['category']=$data->CategoryCode;
			  $item[$i]['parent_category']=$data->ParentCategoryCode;
			  $item[$i]['category_name']=$data->CategoryName;
			  $item[$i]['parent_category_name']=$data->ParentCategoryName;
			  $item[$i]['stock_status']=$data->StockStatusWord;
			  $item[$i]['dod_from']=$data->DodFrom;
  			  $item[$i]['dod_to']=$data->DodTo;
  			  if (trim($data->FixedPrice) == '0'){
	      		  $item[$i]['fixed_price']='オープンプライス';
  			  }
  			  else{
	  			  $item[$i]['fixed_price']=number_format(trim($data->FixedPrice)). '円';
      		  }
      		  $item[$i]['default_price']=number_format(trim($data->DefaultProfitPrice)). '円';
	      	  
  			  $item[$i]['default_Rate']=trim($data->DefaultProfitRate). '%';
          	  $item[$i]['recommended_price']=number_format(trim($data->RecommendedPrice)). '円';
          	  $item[$i]['minimum_price']=number_format(trim($data->MinimumPrice)). '円';
              $item[$i]['wholesale_price']=number_format(trim($data->WholesalePrice)). '円';
              $item[$i]['shop_price']=number_format(trim($data->ShopPrice)). '円';
              $item[$i]['shop_id']=$shopid ;
              $item[$i]['isnewly']=number_format((int)$data->IsNewly);
              $item[$i]['heavyseller']=number_format((int)$data->HeavySeller);
              $item[$i]['isdeliverysameday']=number_format((int)$data->IsDeliverySameday);
              $item[$i]['hasmaterial']=number_format((int)$data->HasMaterial);
              $item[$i]['catchcopy']=$data->CatchCopy;
			  $item[$i]['preorderflag']=trim($data->PreorderFlag);
              $item[$i]['preorderperiod']=trim($data->PreorderPeriod);
              $item[$i]['isfreeshipping']=trim($data->IsFreeShipping);
              
              $i++;
		   }
        }
                
		//画面表示
       $this->set('results', $item);
       
       $page_index_show = $page_index + 1 ;
       $page_next = $page_index + 1 ;
       $page_pre = $page_index - 1 ;
       
       $this->set('all_count', $i);
       $this->set('page_index', $page_index_show);
       $this->set('page_pre', $page_pre);
       $this->set('page_next', $page_next);
       $this->set('page_all', ceil($Totalcount / $list_per_page));
	   
	    //画面遷移
		$this->render('searchdsp');
		
	}
	
	//----------------------------------------------------------------
	//PayPalコールバックアクション
	//----------------------------------------------------------------
	function _paypalcallback(){
		
		$req = 'cmd=_notify-synch';
		$tx_token = $_GET['tx'];
		$auth_token = "GX_sTf5bW3wxRfFEbgofs88nQxvMQ7nsI8m21rzNESnl_79ccFTWj2aPgQ0";
		$req .= "&tx=$tx_token&at=$auth_token";
		
		$results = $socket->post(PAYPAL_DEFAULT_URL. $req);
        $getxml = simplexml_load_string($results); 
		
	}
	
	//----------------------------------------------------------------
	//使用方法解説表示画面
	//----------------------------------------------------------------
	function help(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　１．メインメニュー
	//----------------------------------------------------------------
	function help_mainmenu(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　１．メインメニュー 　画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　２．ユーザ登録方法
	//----------------------------------------------------------------
	function help_userregist(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　２．ユーザ登録方法 　画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　３．ユーザ登録変更削除方法
	//----------------------------------------------------------------
	function help_userdel(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　３．ユーザ登録変更削除方法　 画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　４．ログイン方法
	//----------------------------------------------------------------
	function help_login(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　４．ログイン方法　 画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　５．検索方法
	//----------------------------------------------------------------
	function help_search(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　５．検索方法　 画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　６．お気に入り商品管理方法
	//----------------------------------------------------------------
	function help_fav(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　６．お気に入り商品管理方法　 画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　７．プレミアム機能
	//----------------------------------------------------------------
	function help_premium(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　７．プレミアム機能　 画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　８．パスワードを忘れた時
	//----------------------------------------------------------------
	function help_repassword(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　８．パスワードを忘れた時　 画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	//----------------------------------------------------------------
	//使用方法解説表示画面　９．推奨環境
	//----------------------------------------------------------------
	function help_environment(){
		$this->_pageTitle(SITE_NAME.' : 使用方法解説　９．推奨環境　 画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	
	//----------------------------------------------------------------
	//更新履歴表示画面
	//----------------------------------------------------------------
	function history(){
		$this->_pageTitle(SITE_NAME.' : 更新履歴画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	
	//----------------------------------------------------------------
	//お問い合わせ表示画面
	//----------------------------------------------------------------
	function contact(){
		$this->_pageTitle(SITE_NAME.' : お問い合わせ画面', true);
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	
	//----------------------------------------------------------------
	//利用規約表示画面
	//----------------------------------------------------------------
	function riyoukiyaku(){
		$this->_pageTitle(SITE_NAME.' : 利用規約画面', true);
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	
	//----------------------------------------------------------------
	//プレミアム登録画面アクション
	//----------------------------------------------------------------
	function premium(){
		$this->_pageTitle(SITE_NAME.' : プレミアム登録画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	
	//----------------------------------------------------------------
	//プレミアム登録画面アクション
	//----------------------------------------------------------------
	function premiumsuccess(){
		$this->_pageTitle(SITE_NAME.' : プレミアム登録完了画面', true);
		
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
	
	//----------------------------------------------------------------
	//閉鎖表示
	//----------------------------------------------------------------
	function closed(){
		$this->_pageTitle(SITE_NAME.' : メンテナンス中です画面', true);
		$shopid = $this->Auth->user('shopid');
		if(!empty($shopid)){
	        $this->set('shopid', $shopid);
		}
	}
}
	
?>